<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;


use app\admin\model\ActivityConsumer;
use app\admin\model\ActivityInvitationLog;
use app\admin\model\ConsumerClaimLog;
use app\admin\model\CouponOrder;
use app\admin\model\GoodsOrder;
use app\admin\model\Order;
use app\admin\model\OrderLog;
use app\admin\model\Platform;
use app\admin\model\StoreAccount;
use app\admin\model\StoreJoinActivity;
use app\admin\model\StreamLog;
use app\admin\model\template\ClaimConsume;
use app\admin\model\TicketOrder;
use app\admin\model\Withdraw;
use app\admin\model\WriteLog;
use app\BaseController;
use app\mobile\service\HornService;
use app\mobile\service\WechatpayService;
use think\App;


/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class Transaction extends BaseController
{


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *  使用优惠券生成订单
     */
   public function buyOrder()
   {
       $request = $this->request;
       $param = $request->param();
       $storeModel =  new \app\admin\model\Store();
       $storeInfo = $storeModel->where(['id' => $param['store_id']])->find();

       if ($storeInfo['is_application'] != 2){
           return result(-1, '商家未进件');
       }
       if (empty($storeInfo['mch_no']) || empty($storeInfo['app_id'])){
           return result(-1, '商户未绑定请联系管理员');
       }
       $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
       $amount = $param['amount'];
       $deductible_amount  = 0;
       $consumer_id = 0;
       $consumerClaimLogInfo  = $consumerInfo=[];
       if (isset($param['id']) && $param['id']){
           $consumer_claim_log = $param['id'];
           $consumerClaimLogInfo =   $consumerClaimLogModel->where(['id' => $param['id']])->find();
           if ($consumerClaimLogInfo['expire_time']< time()){
               return result(-1, '消费券/优惠券已过期');
           }
           if ($consumerClaimLogInfo['status'] != 1){
               return result(0, '此券无法使用',[]);
           }
           if ($consumerClaimLogInfo['store_id']){
               if ($param['store_id'] !=$consumerClaimLogInfo['store_id'] ){
                   return result(0, '此优惠券不属于本店',[]);
               }

           }
           if ($consumerClaimLogInfo['activity_id']){
               $storeJoinAccount = new StoreJoinActivity();
               $storeJoinInfo  = $storeJoinAccount->where(['store_id' => $param['store_id'],'activity_id' => $consumerClaimLogInfo['activity_id']])->find();
               if (empty($storeJoinInfo)){
                   return result(0, '本店铺未参与此活动，该券无法使用',[]);
               }
           }
           $consumerModel  =  new \app\admin\model\Consumer();
           $consumerInfo =   $consumerModel->where(['id' => $consumerClaimLogInfo['consumer_id']])->find();
           $consumer_id  = $consumerInfo['id'];
           if ( $consumerInfo['satisfy_amount']> 0 && $param['amount'] < $consumerInfo['satisfy_amount']){
               return result(-1, '未满足使用条件');
           }
           if ($consumerInfo['issue_type'] == 1){
               $amount = bcsub( $param['amount'],$consumerInfo['deductible_amount'],2);
               $deductible_amount  = $consumerInfo['deductible_amount'];
           }elseif ($consumerInfo['issue_type'] == 2){
               $amount = bcdiv(bcmul( $param['amount'],$consumerInfo['deductible_amount'],2),100,2);
               $deductible_amount  = bcsub($param['amount'],$amount,2);
           }else{
               $amount =  0;
               $deductible_amount  =0;
           }

       }else{
           $consumer_claim_log = 0;
       }
       $mchOrderNo =    getPayNo('con');
       $data = [
          // 'uid' => $param['uid'],
           'store_id' =>  $param['store_id'],
           'total_amount' =>  $param['amount'],
           'consumer_claim_log' => $consumer_claim_log,
           'consumer_id' =>  $consumer_id,
           'way_code' => $param['way_code'],
           'deductible_amount' => $deductible_amount,
           'pay_amount' => $amount,
           'order_number' => $mchOrderNo,
           'pay_status' => 1,
           'type'  => isset($consumerClaimLogInfo['type'])? $consumerClaimLogInfo['type'] : 0 ,
           'platform_id'  => isset($storeInfo['platform_id'])? $storeInfo['platform_id'] : 0 ,
           'activity_id'  => isset($consumerClaimLogInfo['activity_id'])? $consumerClaimLogInfo['activity_id'] : 0 ,
           'issue_type' => isset($consumerClaimLogInfo['issue_type'])? $consumerClaimLogInfo['issue_type'] : 0 ,
           'write_type' =>  1 ,
           'send_way' => isset($consumerClaimLogInfo['send_way'])? $consumerClaimLogInfo['send_way'] : 0 ,


          // 'account_id' => $param['account_id'],
       ];
       if (isset( $param['uid']) && $param['uid'] ){
           $data['uid'] =  $param['uid'];
       }else{
           if (isset( $param['telphone']) && $param['telphone'] ){
               $userModel = new \app\admin\model\User();
               $userInfo = $userModel->where(['telphone' =>  $param['telphone']])->find();
               if ($userInfo){
                   $data['uid'] =  $userInfo['id'];
               }else{
                   $domain = $request->domain();

                   $userModel->save([
                       'telphone' =>  $param['telphone'],
                       'avatar' => $domain . "/imgs/def_user.png",
                       'nickname' =>'用户' . substr( $param['telphone'], -4)
                   ]);
                   $data['uid'] =  $userModel->id;
               }

           }
       }
       $data['subsidy_amount'] = 0;
       if ($consumerInfo){
           if ($consumerInfo['store_undertake_proportion'] > 0){
               // 平台补贴
               $subsidy_amount = bcdiv(bcmul( $deductible_amount, $consumerInfo['store_undertake_proportion'],2),100,2);

               $undertake_amount  = bcsub($deductible_amount,$subsidy_amount,2);
               $data['undertake_proportion']  = $consumerInfo['store_undertake_proportion'];
               $data['undertake_amount']  =  $undertake_amount;
               $data['subsidy_amount']  = $subsidy_amount;
           }else{
               $data['undertake_proportion']  = 0;
               $data['undertake_amount']  = $deductible_amount;
               $data['subsidy_amount']  = 0;
           }
       }
       if ( $data['subsidy_amount']> 0){
           $data['subsidy_status']  = 1;
       }else{
           $data['subsidy_status']  = 0;
       }
       $orderModel =  new Order();
       $orderModel->save($data);
       if ($data['pay_amount'] > 0){
           if ($data['activity_id']){
               $activityModel = new \app\admin\model\Activity();
               $activityModel->where(['id' =>$data['activity_id'] ])->inc('cancel_number')->update();
           }
           return result(0, '订单添加成功',['id' => $orderModel->id,'code' => 1]);
       }else{
           $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
           if ($consumer_claim_log){
               $consumerClaimLogModel->where(['id' =>$consumer_claim_log])
                   ->update(['status' => 2,
                       'write_store_id'=> $param['store_id'],
                       //'account_id'=> $param['account_id'],
                   ]);
           }
           if ($consumer_claim_log){
               $writeData = [
                   'uid' =>    $data['uid'],
                   'store_id' =>  $param['store_id'],
                   'platform_id'  => isset($storeInfo['platform_id'])? $storeInfo['platform_id'] : 0 ,
                   'activity_id'  => isset($consumerClaimLogInfo['activity_id'])? $consumerClaimLogInfo['activity_id'] : 0 ,
                   'deductible_amount' => $deductible_amount,
                   'pay_amount' => $param['pay_amount'],
                   'order_number' => $mchOrderNo,
                   'total_amount' =>  $param['amount'],
                   'consumer_claim_log' => $consumer_claim_log,
                   'consumer_id' =>  $consumer_id,
                   'way_code' => $param['way_code'],
                   'type'  => isset($consumerClaimLogInfo['type'])? $consumerClaimLogInfo['type'] : 0 ,
                   'undertake_proportion' => $data['undertake_proportion'],
                   'undertake_amount' => $data['undertake_amount'],
                   'subsidy_amount' => $data['subsidy_amount'],
                   'subsidy_status'  =>  $data['subsidy_status'],
                   'issue_type' => isset($consumerClaimLogInfo['issue_type'])? $consumerClaimLogInfo['issue_type'] : 0 ,
                   'write_type' =>  1 ,
                   'send_way' => isset($consumerClaimLogInfo['send_way'])? $consumerClaimLogInfo['send_way'] : 0 ,
               ];
               $writeLogModel =  new writeLog();
               $writeLogModel->save($writeData);
            }


           return result(0, '核销成功',['id' => $orderModel->id,'code' => 0]);
       }


   }
    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 优惠券支付
     */
    public function payOrder()
    {
        $request = $this->request;
        $param = $request->param();
        $orderModel =  new Order();
        $orderInfo = $orderModel-> where(['id' => $param['id']])->find();
        $storeModel =  new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' => $orderInfo['store_id']])->find();
        $platformModel = new Platform();
        $platformInfo = $platformModel->where(['id' =>$storeInfo['platform_id'] ])->find();
        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->where(['id' => $orderInfo['uid']])->find();
        $domain = $request->domain();
        $requestData  =  [
            'mchNo' => $storeInfo['mch_no'],
            'appId' => $storeInfo['app_id'],
            'mchOrderNo' =>  $orderInfo['order_number'],
            'wayCode' => $orderInfo['way_code'],
            'amount' => intval($orderInfo['pay_amount'] *100),
            'currency' =>'CNY',
            'notifyUrl'=> $domain . '/mobile/transaction/notify',
            'subject' => '优惠券抵扣订单',
            'body'=> '优惠券抵扣订单',
            'reqTime' => time() * 1000,
            'version' => '1.0',
            'signType'=> 'MD5',
            'divisionMode' => 1
          //  'channelExtra' => json_encode(['openid' =>$userInfo['openid'] ])

        ];
        $orderModel-> where(['id' => $param['id']])->update(['pay_way' => $param['pay_way']]);
        if ($orderInfo['way_code'] =='QR_CASHIER'){

        }else{
            if ($platformInfo['pay_type'] == 2){
                $channelExtra = [
                    'openid' => $userInfo['openid'],
                    'subAppId' =>$platformInfo['pay_service_appid']
                ];
            }else{
                $channelExtra = ['openid' => $userInfo['openid']];
            }
            $requestData['channelExtra'] = json_encode($channelExtra);
        }

        ksort($requestData);
        $dataString= '';
       // $dataString = http_build_query($requestData);
        foreach ($requestData as $key => $v){
            $dataString.= $key.'='.$v.'&';
        }
        $dataString .= 'key='.$storeInfo['private_key'];
        $sign =  strtoupper(md5($dataString));
        $requestData['sign'] = $sign;

        $result  = jsonPost('https://pay.ympay.cn/api/pay/unifiedOrder',[],$requestData);
        $resultData = json_decode($result,true);

        if ($resultData['code'] ==0){
            if ($orderInfo['way_code'] =='WX_LITE'){
                return result(0, '成功',json_decode($resultData['data']['payData']),true);

            }else{
                return result(0, '成功',$resultData['data']);
            }
        }else{
            return result(-1, '失败');

        }
    }
    /**
     *  优惠券订单支付回调
     */
    public function  notify(){

        $request = $this->request;
        $param = $request->param();
        file_put_contents('./log/' . date('Y-m-d') . 'orderNotify.txt', json_encode($param) . PHP_EOL, FILE_APPEND);

        $orderModel =  new Order();
        $orderInfo = $orderModel -> where(['order_number' => $param['mchOrderNo']])->find();
        if ($orderInfo['pay_status'] != 1 ){
            echo 'success ';exit;
        }
        $orderModel -> where(['order_number' => $param['mchOrderNo']])->update(['pay_status' => 2,'pay_time'=> time()]);
        $streamLogModel = new StreamLog();
        $platformModel = new Platform();
        $storeModel = new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' =>$orderInfo['store_id'] ])->find();
        $platformInfo  =$platformModel->where(['id' => $orderInfo['platform_id']])->find();
        $siteSet = sysconfig('site');
        $storeHandlingFee = round(bcdiv(bcmul($orderInfo['pay_amount'] ,$storeInfo['application_rate'],4), 100,4),2);
        // 店铺实际到账
        $streamLog['actual_amount']  = round(bcsub($orderInfo['pay_amount'],$storeHandlingFee,4),2);
        // 总平台手续费
        $streamLog['system_application_rate'] = $siteSet['application_rate'];
        $streamLog['system_handling_fee'] = round(bcdiv(bcmul($orderInfo['pay_amount'], $siteSet['application_rate'], 4), 100, 4),2);
        // 平台抽成
        $streamLog['platform_application_rate']  = $platformInfo['application_rate'];
        $streamLog['platform_handling_fee'] = round(bcsub($storeHandlingFee, $streamLog['system_handling_fee'],4),2);
        $streamLog['uid']  = $orderInfo['uid'];
        $streamLog['order_number'] = $orderInfo['order_number'];
        $streamLog['order_amount'] = $orderInfo['pay_amount'];
        $streamLog['platform_id'] = $orderInfo['platform_id'];
        $streamLog['store_id'] = $orderInfo['store_id'];
        $streamLog['order_type'] = 1;
        $streamLogModel->save(  $streamLog);
       if ($orderInfo['consumer_claim_log']>0){
           $writeData = [
               'uid' =>    $orderInfo['uid'],
               'store_id' =>  $orderInfo['store_id'],
               'platform_id'  => isset($storeInfo['platform_id'])? $storeInfo['platform_id'] : 0 ,
               'activity_id'  => isset($orderInfo['activity_id'])? $orderInfo['activity_id'] : 0 ,
               'deductible_amount' => $orderInfo['deductible_amount'],
               'pay_amount' => $orderInfo['pay_amount'],
               'order_number' => $orderInfo['order_number'],
               'total_amount' =>  $orderInfo['total_amount'],
               'consumer_claim_log' => $orderInfo['consumer_claim_log'],
               'consumer_id' =>  $orderInfo['consumer_id'],
               'way_code' => $orderInfo['way_code'],
               'type'  => isset($orderInfo['type'])? $orderInfo['type'] : 0 ,
               'undertake_proportion' => $orderInfo['undertake_proportion'],
               'undertake_amount' => $orderInfo['undertake_amount'],
               'subsidy_amount' => $orderInfo['subsidy_amount'],
               'subsidy_status'  =>  $orderInfo['subsidy_status'],
               'issue_type' => isset($orderInfo['issue_type'])? $orderInfo['issue_type'] : 0 ,
               'write_type' =>  1 ,
               'send_way' => isset($orderInfo['send_way'])? $orderInfo['send_way'] : 0 ,
              // 'account_id' => $orderInfo['account_id'],
           ];
           $writeLogModel =  new writeLog();
           $writeLogModel->save($writeData);
           $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
           $consumerClaimLogModel->where(['id' =>$orderInfo['consumer_claim_log']])->update(['status' => 2,
                   'write_store_id'=> $orderInfo['store_id']]);
           if ($orderInfo['activity_id']){
               $activityModel = new \app\admin\model\Activity();
               $activityModel->where(['id' =>$orderInfo['activity_id'] ])->inc('cancel_number')->update();
           }
       }
       $data = [
           'uid' => $orderInfo['uid'],
           'store_id' =>  $orderInfo['store_id'],
           'total_amount' =>  $orderInfo['total_amount'],
           'way_code' => $orderInfo['way_code'],
           'deductible_amount' => $orderInfo['deductible_amount'],
           'pay_amount' => $orderInfo['pay_amount'],
           'order_number' => $orderInfo['order_number'],
           'type'  => isset($orderInfo['type'])? $orderInfo['type'] : 0 ,
           'platform_id'  => isset($orderInfo['platform_id'])? $orderInfo['platform_id'] : 0 ,
           'issue_type' => $orderInfo['issue_type'],
           'buy_type' => 1,
           'goods_id' => $orderInfo['goods_id'],
          // 'account_id' => $orderInfo['account_id'],
           'pay_way' => $orderInfo['pay_way'],
           'write_type' => $orderInfo['write_type'],
       ];
       $orderLogModel = new OrderLog();
       $orderLogModel->save($data);
       $userModel = new \app\admin\model\User();
       $userInfo = $userModel->where(['id' => $storeInfo['uid']])->find();
       $templateModel   = new \app\admin\model\Template();
       $templateInfo = $templateModel->where(['name'=>'payment',
           'platform_id'=> $storeInfo['platform_id']])->find();
       $hornService = new HornService();
       if ($storeInfo['horn_devid']){
           if ($orderInfo['pay_way'] == ' aliyun'){
               $message = '购买商品收款'.bcmul($orderInfo['pay_amount'],100);
               $hornService->message($storeInfo['horn_devid'],$message);
           }else{
               $message = '购买商品收款'.bcmul($orderInfo['pay_amount'],100);
               $hornService->message($storeInfo['horn_devid'],$message);
           }

       }

       if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
           if ($userInfo['openid']){
               $sendData = [
                   'template_id' => $templateInfo['template_id'],
                   'appid' => $platformInfo['xcx_appid'],
                   'appsecret' => $platformInfo['xcx_appsecret'],
                   'openid' => $userInfo['openid'],
                   'name' => '商品购买',
                   'amount' => $orderInfo['pay_amount']
               ];

               $Payment = new \app\admin\model\template\Payment();
               $Payment->send($sendData);
           }
       }

       echo 'success ';exit;

      // $consumerModel  =  new \app\admin\model\Consumer();
       //$consumerModel->where(['id' => $orderInfo])->inc()

   }


    public function buyGoods()
    {
        $request = $this->request;
        $param = $request->param();
        $GoodsModel =  new \app\admin\model\Goods();
        $goodsInfo = $GoodsModel->where(['id' => $param['goods_id']])->find();
        $storeModel =  new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' => $goodsInfo['store_id']])->find();
        if ($storeInfo['is_application'] != 2){
            return result(-1, '商家未进件');
        }
        if (empty($storeInfo['mch_no']) || empty($storeInfo['app_id'])){
            return result(-1, '商户未绑定请联系管理员');
        }
        $mchOrderNo =    getPayNo('g');
        $data = [
             'uid' => $param['uid'],
            'store_id' =>  $storeInfo['id'],
            'goods_id' =>  $param['goods_id'],
            'price' =>  $goodsInfo['price'],
            'platform_id'  => isset($storeInfo['platform_id'])? $storeInfo['platform_id'] : 0 ,
            'order_number' => $mchOrderNo,
            'pay_status' => 1,
            'way_code' =>  $param['way_code'] ,
            'code' =>  goodsCode(),
            'is_use' => 0,
            'pay_amount' =>  $goodsInfo['price'],
        ];
        $orderModel = new \app\admin\model\GoodsOrder();
        $orderModel-> save($data);
        $web_share_img  = common_qr_code($orderModel->id.'&'.'3','store', $storeInfo['platform_id']);
        $orderModel->where(['id' => $orderModel->id])->update(['web_share_img' =>$web_share_img ]);
        if ($data['price'] > 0){
            return result(0, '订单添加成功',['id' => $orderModel->id,'code' => 1]);
        }else{
            $orderModel->where(['id' => $orderModel->id])->update(['pay_status' =>2,'is_use' => 1 ]);
            return result(0, '购买成功',['id' => $orderModel->id,'code' => 0]);
        }
    }



    public function payGoodsOrder()
    {
        $request = $this->request;
        $param = $request->param();
        $orderModel =  new GoodsOrder();
        $orderInfo = $orderModel-> where(['id' => $param['id']])->find();
        $storeModel =  new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' => $orderInfo['store_id']])->find();
        $platformModel = new Platform();
        $platformInfo = $platformModel->where(['id' =>$storeInfo['platform_id'] ])->find();
        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->where(['id' => $orderInfo['uid']])->find();
        $domain = $request->domain();
        $requestData  =  [
            'mchNo' => $storeInfo['mch_no'],
            'appId' => $storeInfo['app_id'],
            'mchOrderNo' =>  $orderInfo['order_number'],
            'wayCode' => $orderInfo['way_code'],
            'amount' => intval($orderInfo['price'] *100),
            'currency' =>'CNY',
            'notifyUrl'=> $domain . '/mobile/transaction/goodsNotify',
            'subject' => '购买商品',
            'body'=> '购买商品',
            'reqTime' => time() * 1000,
            'version' => '1.0',
            'signType'=> 'MD5',
            'divisionMode' => 1
            //  'channelExtra' => json_encode(['openid' =>$userInfo['openid'] ])
        ];
        $orderModel-> where(['id' => $param['id']])->update(['pay_way' => $param['pay_way']]);
        if ($orderInfo['way_code'] =='QR_CASHIER'){

        }else{
            if ($platformInfo['pay_type'] == 2){
                $channelExtra = [
                    'openid' => $userInfo['openid'],
                    'subAppId' =>$platformInfo['pay_service_appid']
                ];
            }else{
                $channelExtra = ['openid' => $userInfo['openid']];
            }
            $requestData['channelExtra'] = json_encode($channelExtra);
        }
        ksort($requestData);
        $dataString= '';

        foreach ($requestData as $key => $v){
            $dataString.= $key.'='.$v.'&';
        }
        $dataString .= 'key='.$storeInfo['private_key'];
        $sign =  strtoupper(md5($dataString));
        $requestData['sign'] = $sign;

        $result  = jsonPost('https://pay.ympay.cn/api/pay/unifiedOrder',[],$requestData);
        $resultData = json_decode($result,true);
        if ($resultData['code'] ==0){
            if ($orderInfo['way_code'] =='WX_LITE'){
                return result(0, '成功',json_decode($resultData['data']['payData']),true);

            }else{
                return result(0, '成功',$resultData['data']);
            }
        }else{
            return result(-1, '失败');

        }
    }

    public function goodsNotify(){
        $request = $this->request;
        $param = $request->param();
        $GoodsOrderModel = new  GoodsOrder();
        $GoodsOrderInfo =  $GoodsOrderModel->where(['order_number' => $param['mchOrderNo']])->find();
        $platformModel = new  Platform();
        $platformInfo = $platformModel->where(['url' => $GoodsOrderInfo['platform_id']])->find();
        if (empty($platformInfo)) {
            return \json([
                "code" => "FAIL",
                "message" => "支付金额有误"
            ]);
        }
        if ( $GoodsOrderInfo['pay_status'] != 1){
            return \json([
                "code" => "SUCCESS",
                "message" => "已成功"
            ]);
        }
        $GoodsOrderModel->where(['id' => $GoodsOrderInfo['id']])->update(['pay_status' => 2,'is_use'=> 1]);
        $storeModel = new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' => $GoodsOrderInfo['store_id']])->find();
        $goodsModel = new \app\admin\model\Goods();
        $goodsModel->where(['id' =>$GoodsOrderInfo['goods_id'] ])->inc('real_sales')->dec('inventory')->update();
        $siteSet = sysconfig('site');
        $storeHandlingFee = round(bcdiv(bcmul($GoodsOrderInfo['price'] ,$storeInfo['application_rate'],4), 100,4),2);
        // 店铺实际到账
        $streamLog['actual_amount']  = round(bcsub($GoodsOrderInfo['price'],$storeHandlingFee,4),2);
        // 总平台手续费
        $streamLog['system_application_rate'] = $siteSet['application_rate'];
        $streamLog['system_handling_fee'] = round(bcdiv(bcmul($GoodsOrderInfo['price'], $siteSet['application_rate'], 4), 100, 4),2);
        // 平台抽成
        $streamLog['platform_application_rate']  = $platformInfo['application_rate'];
        $streamLog['platform_handling_fee'] = round(bcsub($storeHandlingFee, $streamLog['system_handling_fee'],4),2);
        $streamLog['uid']  = $GoodsOrderInfo['uid'];
        $streamLog['order_number'] = $GoodsOrderInfo['order_number'];
        $streamLog['order_amount'] = $GoodsOrderInfo['price'];
        $streamLog['platform_id'] = $GoodsOrderInfo['platform_id'];
        $streamLog['store_id'] = $GoodsOrderInfo['store_id'];
        $streamLog['order_type'] = 3;
        $streamLogModel = new StreamLog();
        $streamLogModel->save($streamLog);
        $OrderLogdata = [
            'uid' => $GoodsOrderInfo['uid'],
            'store_id' =>  $GoodsOrderInfo['store_id'],
            'total_amount' =>  $GoodsOrderInfo['price'],
            'way_code' => $GoodsOrderInfo['way_code'],
            'deductible_amount' => 0,
            'pay_amount' => $GoodsOrderInfo['price'],
            'order_number' => $GoodsOrderInfo['order_number'],
            'type'  => 0 ,
            'platform_id'  => isset($GoodsOrderInfo['platform_id'])? $GoodsOrderInfo['platform_id'] : 0 ,
            'issue_type' => 0,
            'buy_type' => 4, // 购买商品
            'write_type' => 0,
            'goods_id' => $GoodsOrderInfo['goods_id'],
        ];
        $orderLogModel = new OrderLog();
        $orderLogModel->save($OrderLogdata);
        $UserModel = new \app\admin\model\User();
        $storeUserInfo = $UserModel->where(['id' => $storeInfo['uid']])->find();
        $hornService = new HornService();
        if ($storeInfo['horn_devid']){
            if ($GoodsOrderInfo['pay_way'] == ' aliyun'){
                $message = '购买商品支付'.bcmul($GoodsOrderInfo['price'],100);
                $hornService->message($storeInfo['horn_devid'],$message);
            }else{
                $message = '购买商品支付'.bcmul($GoodsOrderInfo['price'],100);
                $hornService->message($storeInfo['horn_devid'],$message);
            }

        }
        $templateModel   = new \app\admin\model\Template();
        $templateInfo = $templateModel->where(['name'=>'payment',
            'platform_id'=> $storeInfo['platform_id']])->find();
        if ($templateInfo){
            if ($storeUserInfo['openid']){
                $sendData = [
                    'template_id' => $templateInfo['template_id'],
                    'appid' => $platformInfo['xcx_appid'],
                    'appsecret' => $platformInfo['xcx_appsecret'],
                    'openid' => $storeUserInfo['openid'],
                    'name' => '购买商品支付',
                    'amount' => $GoodsOrderInfo['price']
                ];
                $Payment = new \app\admin\model\template\Payment();
                $Payment->send($sendData);
            }
        }

        echo 'success ';exit;
    }


    public function goodsOrderList (){
        $request = $this->request;
        $param = $request->param();
        $couponOrderModel = new \app\admin\model\GoodsOrder();
        //  $where[]  =['platform_id' ,'=', $request->platform_id];
        $where[]  =['pay_status' ,'=', 2];
        if (isset($param['uid']) && $param['uid'] ){
            $where[]  = ['goods_order.uid' ,'=', $param['uid']];
        }
        if (isset($param['store_id']) && $param['store_id'] ){
            $where[]  = ['store_id' ,'=', $param['store_id']];
        }
        if (isset($param['is_use']) &&$param['is_use'] ){
            $where[]  = ['is_use' ,'=', $param['is_use']];

        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $couponOrderModel
            ->withJoin(['userInfo','goodsInfo','storeInfo'], 'LEFT')

            ->where($where)->count();
        if ($total) {
            $list = $couponOrderModel
                ->withJoin(['userInfo','goodsInfo','storeInfo'], 'LEFT')
                ->where($where)->order('create_time', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);
        $data['pay_amount'] = $couponOrderModel->where(['pay_status' => 2])->sum('pay_amount');
        $data['wait_use'] = $couponOrderModel->where(['is_use' => 1])->count();
        $data['already_use'] = $couponOrderModel->where(['is_use' => 2])->count();

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function  goodsOrderInfo(){
        $request = $this->request;
        $param = $request->param();
        $goodsOrderModel = new \app\admin\model\GoodsOrder();

        $goodsOrderInfo = $goodsOrderModel ->withJoin(['userInfo','goodsInfo','storeInfo'], 'LEFT')
            ->where(['goods_order.id' =>$param['id']])->find();

        return result(0, '获取成功',$goodsOrderInfo);



    }


    // 核销记录
   public function orderList(){
       $request = $this->request;
       $param = $request->param();
       $orderModel =  new WriteLog();
       $pindex = max(1, intval(input('page')));
       $psize = empty(input('psize')) ? 10 : intval(input('psize'));
       $where = [];
       if (isset($param['store_id']) &&  $param['store_id']){
           $where[] = ['store_id', '=',$param['store_id'] ];
       }
       if (isset($param['account_id']) &&  $param['account_id']){
           $accountModel = new StoreAccount();
           $accountInfo = $accountModel->where(['id' =>$param['account_id'] ])->find();
           if ($accountInfo['type'] == 2){
               $where[] = ['account_id', '=',$param['account_id'] ];
           }else{
               $where[] = ['store_id', '=',$accountInfo['store_id'] ];
           }

       }
       if (isset($param['uid']) && $param['uid']){
           $where[] = ['uid', '=',$param['uid'] ];

       }
       if (isset($param['write_type'])&& $param['write_type']){
           $where[] = ['write_type', '=',$param['write_type'] ];
       }
       if (isset( $param['order_number'])  && $param['order_number']){
           $where[] = ['order_number', '=',$param['order_number'] ];

       }
       if (isset( $param['type'])  && $param['type']){

           $where[] = ['type', '=',$param['type']];
       }

       if (isset( $param['send_way'])  && $param['send_way']){

           $where[] = ['send_way', '=',$param['send_way']];
       }
       if (isset( $param['pay_way'])  && $param['pay_way']){
           $where[] = ['pay_way', '=',$param['pay_way']];
       }
       if (isset( $param['start_time'])  && $param['start_time']){
            $zuixiao =  strtotime($param['start_time']);
            $zuida = strtotime(date('Y-m-d')." +1 month -1 day");
            $where[] = ['create_time', '>=',$zuixiao ];
            $where[] = ['create_time', '<=',$zuida ];
       }

       $total = $orderModel  ->where($where)->count();
       $list = $orderModel ->where($where)
           ->limit(($pindex - 1) * $psize, $psize)
          ->order('create_time', 'desc')->select();
       $totalPage = ceil($total / $psize);
       foreach ($list as $key => $value){
          $StoreAccountModel  =  new StoreAccount();
           $list[$key]['account_telphone'] ='';
           $list[$key]['name'] ='';
          if ($value['account_id']){
              $account = $StoreAccountModel->where(['id' => $value['account_id']])->find();
              $list[$key]['account_telphone'] =$account['telphone'];
              $list[$key]['account_name'] =$account['name'];
          }else{
              $StoreModel  =  new \app\admin\model\Store();
              $Store = $StoreModel->where(['id' => $value['store_id']])->find();
              $list[$key]['account_telphone'] =$Store['telphone'];
              $list[$key]['account_name'] =$Store['store_name'];
          }
           $UserModel  =  new \app\admin\model\User();
           $list[$key]['user_telphone'] ='';
           $list[$key]['user_name'] = '';
           if ($value['operation_uid']){
               $UserInfo = $UserModel->where(['id' => $value['operation_uid']])->find();
               $list[$key]['user_telphone'] =$UserInfo['telphone'];
               $list[$key]['user_name'] =$UserInfo['nickname'];
           }

//           if ($value['store_id']){
//               $StoreModel  =  new \app\admin\model\Store();
//               $Store = $StoreModel->where(['id' => $value['store_id']])->find();
//               $list[$key]['store_telphone'] =$Store['telphone'];
//               $list[$key]['store_name'] =$account['store_name'];
//           }else{
//               $list[$key]['store_telphone'] = '';
//               $list[$key]['store_name'] ='';
//           }
           $consumerModel = new \app\admin\model\Consumer();
           $list[$key]['consumerInfo'] = $consumerModel->where(['id'=>$value['consumer_id'] ])->find();
           $list[$key]['consumerInfo']['expire_time'] = date('Y-m-d', $list[$key]['consumerInfo']['expire_time']);
       }

               $totalArray['consumer_total']  =$total;
               $totalArray['activity_consumer_total']  =$orderModel->where($where)->where(['send_way' => 1])->count();
               $totalArray['store_consumer_total']  =$orderModel->where($where)->where(['send_way' => 2])->count();
               $totalArray['coupon_consumer_total']  =$orderModel->where($where)->where(['send_way' => 3])->count();
               $totalArray['ticket_consumer_total']  =$orderModel->where($where)->where(['send_way' =>4])->count();
               $totalArray['store_subsidy_amount']  = $orderModel->where($where)->where(['subsidy_status' =>4])->sum('subsidy_amount');

       //           }

       return result(0, 'success', array(
           'list' => $list,
           'total' => $total,
           'statistics' => $totalArray,
           'pindex' => $pindex,
           'psize' => $psize,
           'totalPage' => $totalPage
       ));
   }


    /**
     * @throws \think\db\exception\DbException
     * 申请补贴
     */
   public function  applySubsidy(){
       $request = $this->request;
       $param = $request->param();
       $orderModel =  new WriteLog();
       $orderModel->where(['id' =>$param['id'] ])->update(['subsidy_status' => 2,'subsidy_img' => $param['subsidy_img']]);

       return result(0, '申请成功，等待审核');
   }


   public function applyWithdraw(){
       $request = $this->request;
       $param = $request->param();

       $platformModel =  new \app\admin\model\Platform();
       $platformInfo = $platformModel->where(['id' => $request->platform_id])->find();

       $data = [
           'platform_id' => $request->platform_id,
           'store_id' => $param['store_id'],
           'withdraw_rate' => $platformInfo['withdraw_rate'],
           'apply_amount' => $param['apply_amount'],
           'handling_fee' =>  bcdiv(bcmul($param['apply_amount'],$platformInfo['withdraw_rate'],2),100,2),
           'type' => $param['type'],
           'account' => $param['account'],
           'name' => $param['name'],
           'bank_name' => isset($param['bank_name']) ? $param['bank_name']:'' ,
       ];
       $data['amount'] = bcsub($data['apply_amount'],$data['handling_fee'],2);
       $withdrawModel =  new \app\admin\model\Withdraw();
       $withdrawModel->save($data);
       $storeModel = new \app\admin\model\Store();
       $storeModel->where(['id' => $param['store_id']])
           ->dec('balance', $param['apply_amount'])
           ->inc('freeze', $param['apply_amount'])
           ->update();
       return result(0, '申请成功，等待审核');
   }


   public function withdrawList(){
       $request = $this->request;
       $param = $request->param();
       $withdrawModel =  new \app\admin\model\Withdraw();
        $pindex = max(1, intval(input('page')));
       $psize = empty(input('psize')) ? 10 : intval(input('psize'));
       if (isset($param['store_id']) && $param['store_id']){
           $where = ['store_id' =>$param['store_id'] ];
       }

       if (isset($param['status'])  && $param['status']){
           $where = ['status' =>$param['status'] ];
       }

       if (isset($param['uid'])){
           $where = ['uid' =>$param['uid'] ];
       }
       $total = $withdrawModel->where($where)->count();
       $list = $withdrawModel->where($where)
           ->limit(($pindex - 1) * $psize, $psize)->select();
       $totalPage = ceil($total / $psize);
       return result(0, 'success', array(
           'list' => $list,
           'total' => $total,
           'pindex' => $pindex,
           'psize' => $psize,
           'totalPage' => $totalPage
       ));
   }


   public function payCoupon(){
       try {
           $request = $this->request;
           $param = $request->param();
           $couponOrderModel = new CouponOrder();
           $couponOrderInfo =   $couponOrderModel->where(['id' => $param['id']])->find();
           $platformModel = new Platform();
           $platformInfo = $platformModel->where(['id' =>$couponOrderInfo['platform_id'] ])->find();
           if (empty($platformInfo['xcx_appid'])){
               return result(- 1, '支付配置有误,请联系管理员' );
           }
           $UserModel = new \app\admin\model\User();
           $userInfo = $UserModel->where(['id' => $couponOrderInfo['uid']])->find();
           $domain = $request->domain();
           $data = [
               'serial_number' => $platformInfo['pay_serial_no'],
               'order_sn' => $couponOrderInfo['order_number'],
               'title'=> '购买卡券',
               'notify_url' => $domain.'/mobile/transaction/couponNotify',
               'price' => $couponOrderInfo['price'],
               'pay_key' => $platformInfo['pay_key']
           ];
           $wechatPayService = new WechatpayService();
           $data['openid'] =  $userInfo['openid'];
           if ($platformInfo['pay_type'] == 2){
               $data['sp_appid'] = $platformInfo['pay_service_appid'];
               $data['sp_mchid'] = $platformInfo['pay_service_mchid'];
               $data['sub_mchid'] = $platformInfo['pay_mchid'];
           }else{
               $data['appid'] = $platformInfo['xcx_appid'];
               $data['mchid'] = $platformInfo['pay_mchid'];
               $result =  $wechatPayService->wechatXcxPay($data);
           }
           if ($result['code'] == 1) {
               return result(0, '成功',$result['data']);
           } else {
               return result(-1,$result['msg']);
           }

       } catch (\Exception $e) {
           return result(- 1, '操作异常:' . $e->getMessage(), $e->getLine());
       }
   }

   public function couponNotify(){

       $getCallBackJson = file_get_contents('php://input');
       file_put_contents('./log/' . date('Y-m-d') . 'couponNotify.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
       $getCallBackArray = json_decode($getCallBackJson, true);
       $associatedData = $getCallBackArray['resource']['associated_data'];
       $nonceStr = $getCallBackArray['resource']['nonce'];
       $ciphertext = $getCallBackArray['resource']['ciphertext'];
       $ciphertext = \base64_decode($ciphertext);
       $ctext = substr($ciphertext, 0, -16);
       $authTag = substr($ciphertext, -16);
       $domain = $_SERVER['HTTP_HOST'];
       $platformModel = new  Platform();
       $platformInfo = $platformModel->where(['url' => $domain])->find();
       if (empty($platformInfo)) {
           return \json([
               "code" => "FAIL",
               "message" => "支付金额有误"
           ]);
       }
       $str = \openssl_decrypt($ctext, 'aes-256-gcm', $platformInfo['pay_api_key'], \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
       $result = json_decode($str, true);;
       if ($result['trade_state'] == 'SUCCESS') {
           $couponOrderModel = new CouponOrder();
           $couponOrderInfo = $couponOrderModel->where(['order_number' => $result['out_trade_no']])->find();
           if ($couponOrderInfo['pay_status'] != 1){
               return \json([
                   "code" => "SUCCESS",
                   "message" => "已成功"
               ]);
           }
           $couponOrderModel->where(['id' => $couponOrderInfo['id']])->update(['pay_status' => 2]);
           $couponConsumerModel = new \app\admin\model\CouponConsumer();
           $couponConsumerList = $couponConsumerModel->where(['coupon_id' => $couponOrderInfo['coupon_id']])->select();
           foreach ($couponConsumerList as $value) {
               $consumerModel = new \app\admin\model\Consumer();
               $consumerClaimLog = new ConsumerClaimLog();
               $consumerInfo = $consumerModel->where(['id' => $value['consumer_id']])->find();
               $couponConsumerData = [
                   'order_number' => $couponOrderInfo['order_number'],
                   'consumer_id' => $value['consumer_id'],
                   'store_id' => $value['store_id'],
                   'platform_id' => $platformInfo['id'],
                   'uid' => $couponOrderInfo['uid'],
                   'type' => 2,
                   'status' => 1,
                   'expire_time' => time()+ ($consumerInfo['expire_time'] *86400 ),
                   'price' =>0,
                   'consumer_type' => $consumerInfo['consumer_type'],
                   'satisfy_amount' => $consumerInfo['satisfy_amount'],
                   'deductible_amount' => $consumerInfo['deductible_amount'],
                   'coupon_id' => $couponOrderInfo['coupon_id'],
                   'order_id' => $couponOrderInfo['id'],
                   'issue_type' => $consumerInfo['issue_type'],
                   'send_way' =>3,
                   'write_store_id' =>  $value['store_id'],
                   'verification_code' =>consumerVerificationCode()
               ];
               $consumerClaimLog->save($couponConsumerData);
               $settlement_code  = common_qr_code($consumerClaimLog->id.'&'.'1','consumer', $platformInfo['id']);
               $consumerClaimLog->where(['id' => $consumerClaimLog->id])->update(['settlement_code' =>$settlement_code ]);

               $consumerModel->where(['id' => $value['consumer_id']])->inc('claimed_number')->update();

               $userModel = new \app\admin\model\User();
               $templateModel = new \app\admin\model\Template();
               $templateInfo = $templateModel->where(['name' => 'claim_consume',
                   'platform_id' => $platformInfo['id']])->find();
               $userInfo = $userModel->where(['id' => $couponOrderInfo['uid']])->find();
               if ( $userInfo['openid']){
                   if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
                       $sendData = [
                           'template_id' => $templateInfo['template_id'],
                           'appid' => $platformInfo['xcx_appid'],
                           'appsecret' => $platformInfo['xcx_appsecret'],
                           'openid' => $userInfo['openid'],
                           'name' => '满' . $consumerInfo['satisfy_amount'] . '减' . $consumerInfo['deductible_amount'],
                           'type_name' =>  '优惠券',
                       ];
                       if ($consumerInfo['issue_type'] == 1){
                           $sendData['name']  ='满'.$consumerInfo['satisfy_amount'].'减'.$consumerInfo['deductible_amount'];

                       }elseif($consumerInfo['issue_type'] == 2){
                           $sendData['name']  ='满'.$consumerInfo['satisfy_amount'].'折扣'.$consumerInfo['deductible_amount'].'%';

                       }else{
                           $sendData['name']  =$consumerInfo['title'];

                       }
                       $ClaimConsumeTemplate = new ClaimConsume();
                       $ClaimConsumeTemplate->send($sendData);
                   }

               }

           }
           $couponModel = new \app\admin\model\Coupon();
           $couponModel->where(['id' =>$couponOrderInfo['coupon_id'] ])->inc('real_sales')->dec('inventory')->update();
           return \json([
               "code" => "SUCCESS",
               "message" => "已成功"
           ]);
       }
   }

   // 平台优惠券购买

    public function platformConsumerPay(){

        try {
            $request = $this->request;
            $param = $request->param();
            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
            $consumerClaimLogInfo  = $consumerClaimLogModel->where(['id'=>$param['id'] ])->find();
            $platformModel = new Platform();
            $platformInfo = $platformModel->where(['id' =>$consumerClaimLogInfo['platform_id'] ])->find();
            if (empty($platformInfo['xcx_appid'])){
                return result(- 1, '支付配置有误,请联系管理员' );
            }
            $UserModel = new \app\admin\model\User();
            $userInfo = $UserModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
            $domain = $request->domain();
            $data = [
                'serial_number' => $platformInfo['pay_serial_no'],
                'order_sn' => $consumerClaimLogInfo['order_number'],
                'title'=> '购买消费券',
                'notify_url' => $domain.'/mobile/transaction/platformConsumerNotify',
                'price' => $consumerClaimLogInfo['price'],
                'pay_key' => $platformInfo['pay_key']
            ];
            $data['openid'] =  $userInfo['openid'];
            $wechatPayService = new WechatpayService();
            if ($platformInfo['pay_type'] == 2){


                $data['sp_appid'] = $platformInfo['pay_service_appid'];
                $data['sp_mchid'] = $platformInfo['pay_service_mchid'];
                //    $data['appid'] = $platformInfo['xcx_appid'];
                $data['sub_mchid'] = $platformInfo['pay_mchid'];

//               if ($param['pay_type'] == 'h5'){
//                   $data['payer_client_ip'] = $_SERVER['REMOTE_ADDR'];
//                   $data['sub_mchid'] = $platformInfo['xcx_mchid'];
//                   $result = $wechatPayService->mWechatPay($data);
//               }else{
                $result =   $wechatPayService->mWechatXcxPay($data);
//               }
            }else{
                $data['appid'] = $platformInfo['xcx_appid'];
                $data['mchid'] = $platformInfo['pay_mchid'];
//               if ($param['pay_type'] == 'h5'){
//                   $data['payer_client_ip'] = $_SERVER['REMOTE_ADDR'];
//                   $result =  $wechatPayService->wechatPay($data);
//               }else{

                $result =  $wechatPayService->wechatXcxPay($data);
//               }
            }
            if ($result['code'] == 1) {
                return result(0, '成功',$result['data']);
            } else {
                return result(-1,$result['msg']);
            }


        } catch (\Exception $e) {
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getLine());
        }

    }

    public function platformConsumerNotify()
    {

        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'platformConsumerNotify.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);

        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $domain = $_SERVER['HTTP_HOST'];
        $platformModel = new  Platform();
        $platformInfo = $platformModel->where(['url' => $domain])->find();
        if (empty($platformInfo)) {
            return \json([
                "code" => "FAIL",
                "message" => "支付金额有误"
            ]);
        }
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', $platformInfo['pay_api_key'], \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $consumerClaimLogModel = new ConsumerClaimLog();

            $consumerClaimLogInfo = $consumerClaimLogModel->where(['order_number' => $result['out_trade_no']])->find();
            if ($result['amount']['total'] != bcmul($consumerClaimLogInfo['price'], 100)) {
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($consumerClaimLogInfo['status'] != 0){
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }

            $consumerClaimLogModel->where(['order_number' => $result['out_trade_no']])->update(['status' => 1]);
            $activityConsumerModel = new ActivityConsumer();
            $activityConsumerInfo  = $activityConsumerModel->where(['id' => $consumerClaimLogInfo['activity_consumer_id']])->find();
            if (   $activityConsumerInfo['claim_number'] >0){
                $activityConsumerModel->where(['id' => $consumerClaimLogInfo['activity_consumer_id']])
                    ->dec('surplus_number')->inc('claimed_number')
                    ->update();
            }else{
                $activityConsumerModel->where(['id' => $consumerClaimLogInfo['activity_consumer_id']])
                    ->inc('claimed_number')
                    ->update();
            }
            $uidClaimCount = $consumerClaimLogModel->where([
                'activity_id' => $consumerClaimLogInfo['activity_id'],
                'uid' => $consumerClaimLogInfo['uid'],
            ])->count();
            $activityModel = new \app\admin\model\Activity();
            $activityInfo = $activityModel->where(['id' => $consumerClaimLogInfo['activity_id']])->find();
            if ($activityInfo['total_claim_number'] > 0 && $activityInfo['total_claim_number'] <= $uidClaimCount) {
                $activityInvitationLogModel = new ActivityInvitationLog();
                $activityInvitationLogInfo = $activityInvitationLogModel
                    ->where([
                        'activity_id' => $consumerClaimLogInfo['activity_id'],
                        'sent_uid' => $consumerClaimLogInfo['uid'],
                    ])->where('surplus_number', '>', 0)->find();
                if ($activityInvitationLogInfo) {
                    $activityInvitationLogModel->where(['id' => $activityInvitationLogInfo['id']])
                        ->dec('surplus_number')->update();
                }
                $consumerModel = new \app\admin\model\Consumer();
                $consumerModel->where(['id' => $consumerClaimLogInfo['consumer_id']])->inc('claimed_number')->update();

                if ( isset($consumerClaimLogInfo['invitation_uid']) && $consumerClaimLogInfo['invitation_uid']){
                    $activityInvitationLogModel->save([
                        'sent_uid' => $consumerClaimLogInfo['invitation_uid'],
                        'uid' => $consumerClaimLogInfo['uid'],
                        'activity_id' => $consumerClaimLogInfo['activity_id'],
                        'claim_number' => $activityInfo['invitation_obtain_frequency'],
                        'surplus_number' => $activityInfo['invitation_obtain_frequency'],
                    ]);
                }
                $activityModel->where(['id' => $activityInfo['id']])->inc('claimed_number')->update();

            }
            $templateModel   = new \app\admin\model\Template();
            $templateInfo = $templateModel->where(['name'=>'claim_consume',
                'platform_id'=> $consumerClaimLogInfo['platform_id']])->find();
            $userModel = new \app\admin\model\User();
            $userInfo = $userModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
            if ( $userInfo['openid']){
                if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
                    $consumerModel  =  new \app\admin\model\Consumer();
                    $ConsumerInfo  = $consumerModel->where(['id' => $consumerClaimLogInfo['consumer_id']])->find();
                    $sendData = [
                        'template_id' => $templateInfo['template_id'],
                        'appid' => $platformInfo['xcx_appid'],
                        'appsecret' => $platformInfo['xcx_appsecret'],
                        'openid' => $userInfo['openid'],
                        //  'name' => '满'.$ConsumerInfo['satisfy_amount'].'减'.$ConsumerInfo['deductible_amount'],
                        'type_name' => '消费券',
                    ];
                    if ($ConsumerInfo['issue_type'] == 1){
                        $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'减'.$ConsumerInfo['deductible_amount'];

                    }elseif($ConsumerInfo['issue_type'] == 2){
                        $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'折扣'.$ConsumerInfo['deductible_amount'].'%';

                    }else{
                        $sendData['name']  =$ConsumerInfo['title'];

                    }
                    $ClaimConsumeTemplate = new ClaimConsume();
                    $ClaimConsumeTemplate->send($sendData);
                }

            }

            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);

        }
    }

    public function  storeConsumerPay(){
       $request = $this->request;
       $param = $request->param();
       $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
       $consumerClaimLogInfo  = $consumerClaimLogModel->where(['id'=>$param['id'] ])->find();
        $consumerClaimLogInfo-> where(['id' => $param['id']])->update(['pay_way' => $param['pay_way']]);
       $storeModel = new \app\admin\model\Store();
       $storeInfo  = $storeModel->where(['id' => $consumerClaimLogInfo['store_id']])->find();
       $platformModel = new Platform();
       $platformInfo = $platformModel->where(['id' =>$storeInfo['platform_id'] ])->find();
       $userModel = new \app\admin\model\User();
       $userInfo = $userModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
       $domain = $request->domain();
        $requestData  =  [
            'mchNo' => $storeInfo['mch_no'],
            'appId' => $storeInfo['app_id'],
            'mchOrderNo' => $consumerClaimLogInfo['order_number'],
            'wayCode' => $consumerClaimLogInfo['way_code'],
            'amount' => intval($consumerClaimLogInfo['price'] *100),
            'currency' =>'CNY',
            'notifyUrl'=> $domain . '/mobile/transaction/storeConsumerNotify',
            'subject' => '优惠券抵扣订单',
            'body'=> '优惠券抵扣订单',
            'reqTime' => time() * 1000,
            'version' => '1.0',
            'signType'=> 'MD5',
            'divisionMode' => 1
            //  'channelExtra' => json_encode(['openid' =>$userInfo['openid'] ])
        ];
       // $channelExtra = ['openid' => $userInfo['openid']];
        if ($platformInfo['pay_type'] == 2){
            $channelExtra = [
                'openid' => $userInfo['openid'],
                'subAppId' =>$platformInfo['pay_service_appid']
            ];
        }else{
            $channelExtra = ['openid' => $userInfo['openid']];
        }
        $requestData['channelExtra'] = json_encode($channelExtra);
        ksort($requestData);

        $dataString= '';
        // $dataString = http_build_query($requestData);
        foreach ($requestData as $key => $v){
            $dataString.= $key.'='.$v.'&';
        }
        $dataString .= 'key='.$storeInfo['private_key'];
        $sign =  strtoupper(md5($dataString));
        $requestData['sign'] = $sign;
        //  var_dump(json_encode($requestData));exit;
        $result  = jsonPost('https://pay.ympay.cn/api/pay/unifiedOrder',[],$requestData);
        $resultData = json_decode($result,true);
        if ($resultData['code'] ==0){
            return result(0, '成功',json_decode($resultData['data']['payData']),true);
        }else{
            return result(-1, '失败');
        }
   }

   public function   storeConsumerNotify(){
       $request = $this->request;
       $param = $request->param();
       file_put_contents('./log/' . date('Y-m-d') . 'storeConsumerNotify.txt', json_encode($param) . PHP_EOL, FILE_APPEND);
       $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
       $consumerClaimLogInfo  = $consumerClaimLogModel->where(['order_number'=>$param['mchOrderNo'] ])->find();
       if ($consumerClaimLogInfo['status'] == 0) {
           $consumerClaimLogInfo = $consumerClaimLogModel
               ->where(['order_number' => $param['mchOrderNo']])->update(['status' => 1]);
           $streamLogModel = new StreamLog();
           $platformModel = new Platform();
           $storeModel = new \app\admin\model\Store();
           $storeInfo = $storeModel->where(['id' => $consumerClaimLogInfo['write_store_id']])->find();
           $platformInfo = $platformModel->where(['id' => $consumerClaimLogInfo['platform_id']])->find();
           $siteSet = sysconfig('site');

           // 店铺手续费
           // 子平台实际到账
           $storeHandlingFee = round(bcdiv(bcmul($consumerClaimLogInfo['price'] ,$storeInfo['application_rate'],4), 100,4),2);
           // 店铺实际到账
           $streamLog['actual_amount']  =round( bcsub($consumerClaimLogInfo['price'],$storeHandlingFee,4),2);
           // 总平台手续费
           $streamLog['system_application_rate'] = $siteSet['application_rate'];
           $streamLog['system_handling_fee'] = round( bcdiv(bcmul($consumerClaimLogInfo['price'], $siteSet['application_rate'], 4), 100, 4));
           // 平台抽成
           $streamLog['platform_application_rate']  = $platformInfo['application_rate'];
           $streamLog['platform_handling_fee'] = round(bcsub($storeHandlingFee, $streamLog['system_handling_fee'],4),2);

           $streamLog['uid']  = $consumerClaimLogInfo['uid'];
           $streamLog['order_number'] = $consumerClaimLogInfo['order_number'];
           $streamLog['order_amount'] = $consumerClaimLogInfo['price'];
           $streamLog['platform_id'] = $consumerClaimLogInfo['platform_id'];
           $streamLog['store_id'] = $consumerClaimLogInfo['write_store_id'];
           $streamLog['order_type'] = 2;


           $hornService = new HornService();
           if ($storeInfo['horn_devid']){
               if ($consumerClaimLogInfo['issue_type'] == 1){
                   if ($consumerClaimLogInfo['pay_way'] == ' aliyun'){
                       $message = '购买抵扣劵收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }else{
                       $message = '购买抵扣劵收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }
               }else if ($consumerClaimLogInfo['issue_type'] == 2){
                   if ($consumerClaimLogInfo['pay_way'] == ' aliyun'){
                       $message = '购买折扣劵收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }else{
                       $message = '购买折扣劵收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }
               }else if ($consumerClaimLogInfo['issue_type'] == 3){
                   if ($consumerClaimLogInfo['pay_way'] == ' aliyun'){
                       $message = '购买商品收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }else{
                       $message = '购买商品收款'.bcmul($consumerClaimLogInfo['price'],100);
                       $hornService->message($storeInfo['horn_devid'],$message);
                   }
               }


           }


           $streamLogModel->save($streamLog);
           $consumerModel = new \app\admin\model\Consumer();
           $ConsumerInfo = $consumerModel->where(['id' => $consumerClaimLogInfo['consumer_id']])->find();
           $consumerModel->where(['id' => $consumerClaimLogInfo['id']])->inc('claimed_number')->update();
           $platformModel = new Platform();
           $platformInfo = $platformModel->where(['id' => $consumerClaimLogInfo['platform_id']])->find();
           $templateModel = new \app\admin\model\Template();
           $templateInfo = $templateModel->where(['name' => 'claim_consume',
               'platform_id' => $consumerClaimLogInfo['platform_id']])->find();
           $userModel = new \app\admin\model\User();

           $orderLogdata = [
               'uid' => $consumerClaimLogInfo['uid'],
               'store_id' => $consumerClaimLogInfo['store_id'],
               'total_amount' => $consumerClaimLogInfo['price'],
               'way_code' => $consumerClaimLogInfo['way_code'],
               'deductible_amount' => 0,
               'pay_amount' => $consumerClaimLogInfo['price'],
               'order_number' => $consumerClaimLogInfo['order_number'],
               'type' => isset($consumerClaimLogInfo['type']) ? $consumerClaimLogInfo['type'] : 0,
               'platform_id' => isset($consumerClaimLogInfo['platform_id']) ? $consumerClaimLogInfo['platform_id'] : 0,
               'issue_type' => $consumerClaimLogInfo['issue_type'],
               'buy_type' => 2,
              // 'account_id' => $consumerClaimLogInfo['account_id'],
               'pay_way' => $consumerClaimLogInfo['pay_way'],
               'write_type' => 1,
           ];
           $orderLogModel = new OrderLog();
           $orderLogModel->save($orderLogdata);
           $userInfo = $userModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
           if ( $userInfo['openid']){
               if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
                   $sendData = [
                       'template_id' => $templateInfo['template_id'],
                       'appid' => $platformInfo['xcx_appid'],
                       'appsecret' => $platformInfo['xcx_appsecret'],
                       'openid' => $userInfo['openid'],
                       'name' => '满' . $ConsumerInfo['satisfy_amount'] . '减' . $ConsumerInfo['deductible_amount'],
                       'type_name' =>  '优惠券',
                   ];
                   if ($ConsumerInfo['issue_type'] == 1){
                       $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'减'.$ConsumerInfo['deductible_amount'];

                   }elseif($ConsumerInfo['issue_type'] == 2){
                       $sendData['name']  ='满'.$ConsumerInfo['satisfy_amount'].'折扣'.$ConsumerInfo['deductible_amount'].'%';

                   }else{
                       $sendData['name']  =$ConsumerInfo['title'];

                   }
                   $ClaimConsumeTemplate = new ClaimConsume();
                   $ClaimConsumeTemplate->send($sendData);
               }

           }

           $storeUserInfo = $userModel->where(['id' => $storeInfo['uid']])->find();
           $templateModel = new \app\admin\model\Template();
           $templateInfo = $templateModel->where(['name' => 'payment',
               'platform_id' => $storeInfo['platform_id']])->find();
           if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
               if ($storeUserInfo['openid']) {
                   $sendBuyData = [
                       'template_id' => $templateInfo['template_id'],
                       'appid' => $platformInfo['xcx_appid'],
                       'appsecret' => $platformInfo['xcx_appsecret'],
                       'openid' => $storeUserInfo['openid'],
                       'name' => '购买优惠券',
                       'amount' => $consumerClaimLogInfo['price']
                   ];

                   $Payment = new \app\admin\model\template\Payment();
                   $Payment->send($sendBuyData);
               }
           }
           echo 'success ';
           exit;
       }
   }

    public function payTicket(){
        try {
            $request = $this->request;
            $param = $request->param();
            $TicketOrderModel =  new TicketOrder();
            $orderInfo = $TicketOrderModel -> where(['id' => $param['id']])->find();
            $storeModel =  new \app\admin\model\Store();
            $storeInfo = $storeModel->where(['id' => $orderInfo['store_id']])->find();
            $domain = $request->domain();
            $requestData  =  [
                'mchNo' => $storeInfo['mch_no'],
                'appId' => $storeInfo['app_id'],
                'mchOrderNo' => $orderInfo['order_number'],
                'wayCode' => $orderInfo['way_code'],
                'amount' => $orderInfo['price'] *100,
                'currency' =>'cny',
                'notifyUrl'=> $domain . '/mobile/transaction/ticketNotify',
                'subject' => 'orderConsumer',
                'body'=> 'orderConsumer',
                'reqTime' => time() * 1000,
                'version' => '1.0',
                'signType'=> 'MD5',
                'divisionMode' => 1
            ];
            $TicketOrderModel-> where(['id' => $param['id']])->update(['pay_way' => $param['pay_way']]);
            $platformModel = new Platform();
            $platformInfo = $platformModel->where(['id' =>$storeInfo['platform_id'] ])->find();
            $userModel = new \app\admin\model\User();
            $userInfo = $userModel->where(['id' => $orderInfo['uid']])->find();
            if ($orderInfo['way_code'] =='QR_CASHIER'){

            }else{
                if ($platformInfo['pay_type'] == 2){
                    $channelExtra = [
                        'openid' => $userInfo['openid'],
                        'subAppId' =>$platformInfo['pay_service_appid']
                    ];
                }else{
                    $channelExtra = ['openid' => $userInfo['openid']];
                }
                $requestData['channelExtra'] = json_encode($channelExtra);
            }
            ksort($requestData);
            $dataString= '';
            // $dataString = http_build_query($requestData);
            foreach ($requestData as $key => $v){
                $dataString.= $key.'='.$v.'&';
            }
            $dataString .= 'key='.$storeInfo['private_key'];
            $sign =  strtoupper(md5($dataString));
            $requestData['sign'] = $sign;
            $result  = jsonPost('https://pay.ympay.cn/api/pay/unifiedOrder',[],$requestData);
            $resultData = json_decode($result,true);
            if ($resultData['code'] ==0){
                if ($orderInfo['way_code'] =='WX_LITE'){
                    return result(0, '成功',json_decode($resultData['data']['payData']),true);
                }else{
                    return result(0, '成功',$resultData['data']);
                }
            }else{
                return result(-1, '失败');
            }
        } catch (\Exception $e) {
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getLine());
        }
    }

    public function ticketNotify(){
        $request = $this->request;
        $param = $request->param();

        $TicketOrderModel = new  TicketOrder();
        $TicketOrderInfo =  $TicketOrderModel->where(['order_number' => $param['mchOrderNo']])->find();
        $platformModel = new  Platform();
        $platformInfo = $platformModel->where(['url' => $TicketOrderInfo['platform_id']])->find();
        if ( $TicketOrderInfo['pay_status'] != 1){
            return \json([
                    "code" => "SUCCESS",
                    "message" => "已成功"
                ]);
        }
        $TicketOrderModel->where(['id' => $TicketOrderModel->id])->update(['pay_status' => 2,'is_use'=> 1]);
        $TicketConsumerModel = new \app\admin\model\CouponConsumer();
        $TicketConsumerList =  $TicketConsumerModel->where([' ticket' =>  $TicketOrderInfo['id']])->select();
        $storeModel = new \app\admin\model\Store();
        $storeInfo = $storeModel->where(['id' => $TicketOrderInfo['store_id']])->find();
        $ticketModel = new \app\admin\model\Ticket();
        $ticketModel->where(['id' =>$TicketOrderInfo['ticket_id'] ])->inc('real_sales')->dec('inventory')->update();
        $siteSet = sysconfig('site');
        $storeHandlingFee = round(bcdiv(bcmul($TicketOrderInfo['price'] ,$storeInfo['application_rate'],4), 100,4),2);
        // 店铺实际到账
        $streamLog['actual_amount']  = round(bcsub($TicketOrderInfo['price'],$storeHandlingFee,4),2);
        // 总平台手续费
        $streamLog['system_application_rate'] = $siteSet['application_rate'];
        $streamLog['system_handling_fee'] = round(bcdiv(bcmul($TicketOrderInfo['price'], $siteSet['application_rate'], 4), 100, 4),2);
        // 平台抽成
        $streamLog['platform_application_rate']  = $platformInfo['application_rate'];
        $streamLog['platform_handling_fee'] = round(bcsub($storeHandlingFee, $streamLog['system_handling_fee'],4),2);
        $streamLog['uid']  = $TicketOrderInfo['uid'];
        $streamLog['order_number'] = $TicketOrderInfo['order_number'];
        $streamLog['order_amount'] = $TicketOrderInfo['price'];
        $streamLog['platform_id'] = $TicketOrderInfo['platform_id'];
        $streamLog['store_id'] = $TicketOrderInfo['store_id'];
        $streamLog['order_type'] = 3;
        $streamLogModel = new StreamLog();
        $streamLogModel->save($streamLog);
        foreach ( $TicketConsumerList as $value) {
            $consumerModel = new \app\admin\model\Consumer();
            $consumerClaimLog = new ConsumerClaimLog();
            $consumerInfo = $consumerModel->where(['id' => $value['consumer_id']])->find();
            $TicketConsumerData = [
                'consumer_id' => $value['consumer_id'],
                'order_number' => $TicketOrderInfo['order_number'],
                'store_id' => $value['store_id'],
                'platform_id' => $platformInfo['id'],
                'uid' =>  $TicketOrderInfo['uid'],
                'type' => 2,
                'status' => 1,
                'expire_time' => time()+ ($consumerInfo['expire_time'] *86400 ),
                'price' =>0,
                'consumer_type' => $consumerInfo['consumer_type'],
                'satisfy_amount' => $consumerInfo['satisfy_amount'],
                'deductible_amount' => $consumerInfo['deductible_amount'],
                'ticket_id' =>  $TicketOrderInfo['ticket_id'],
                'order_id' =>  $TicketOrderInfo['id'],
                'issue_type' => $consumerInfo['issue_type'],
                'send_way' =>4,
                'write_store_id' =>  $value['store_id'],
                'verification_code' =>consumerVerificationCode()
            ];
            $consumerClaimLog->save( $TicketConsumerData);
            $settlement_code  = common_qr_code($consumerClaimLog->id.'&'.'1','consumer',  $platformInfo['id']);
            $consumerClaimLog->where(['id' => $consumerClaimLog->id])->update(['settlement_code' =>$settlement_code ]);
            $consumerModel->where(['id' => $value['consumer_id']])->inc('claimed_number')->update();

            $userModel = new \app\admin\model\User();
            $templateModel = new \app\admin\model\Template();
            $templateInfo = $templateModel->where(['name' => 'claim_consume',
                'platform_id' => $platformInfo['id']])->find();
            $userInfo = $userModel->where(['id' => $TicketOrderInfo['uid']])->find();
            if ( $userInfo['openid']){
                if (isset($templateInfo['template_id']) && $templateInfo['template_id']){
                    $sendData = [
                        'template_id' => $templateInfo['template_id'],
                        'appid' => $platformInfo['xcx_appid'],
                        'appsecret' => $platformInfo['xcx_appsecret'],
                        'openid' => $userInfo['openid'],
                        'name' => '满' . $consumerInfo['satisfy_amount'] . '减' . $consumerInfo['deductible_amount'],
                        'type_name' =>  '优惠券',
                    ];
                    if ($consumerInfo['issue_type'] == 1){
                        $sendData['name']  ='满'.$consumerInfo['satisfy_amount'].'减'.$consumerInfo['deductible_amount'];

                    }elseif($consumerInfo['issue_type'] == 2){
                        $sendData['name']  ='满'.$consumerInfo['satisfy_amount'].'折扣'.$consumerInfo['deductible_amount'].'%';

                    }else{
                        $sendData['name']  =$consumerInfo['title'];

                    }
                    $ClaimConsumeTemplate = new ClaimConsume();
                    $ClaimConsumeTemplate->send($sendData);
                }

            }
        }
        $OrderLogdata = [
            'uid' => $TicketOrderInfo['uid'],
            'store_id' =>  $TicketOrderInfo['store_id'],
            'total_amount' =>  $TicketOrderInfo['price'],
            'way_code' => $TicketOrderInfo['way_code'],
            'deductible_amount' => 0,
            'pay_amount' => $TicketOrderInfo['price'],
            'order_number' => $TicketOrderInfo['order_number'],
            'type'  => 0 ,
            'platform_id'  => isset($TicketOrderInfo['platform_id'])? $TicketOrderInfo['platform_id'] : 0 ,
            'issue_type' => 0,
            'buy_type' => 3,
            'write_type' => 0
        ];
        $orderLogModel = new OrderLog();
        $orderLogModel->save($OrderLogdata);
        $UserModel = new \app\admin\model\User();
        $storeUserInfo = $UserModel->where(['id' => $storeInfo['uid']])->find();
        $hornService = new HornService();
        if ($storeInfo['horn_devid']){
            if ($TicketOrderInfo['pay_way'] == ' aliyun'){
                $message = '购买票根支付'.bcmul($TicketOrderInfo['price'],100);
                $hornService->message($storeInfo['horn_devid'],$message);
            }else{
                $message = '购买票根支付'.bcmul($TicketOrderInfo['price'],100);
                $hornService->message($storeInfo['horn_devid'],$message);
            }

        }
        $templateModel   = new \app\admin\model\Template();
        $templateInfo = $templateModel->where(['name'=>'payment',
            'platform_id'=> $storeInfo['platform_id']])->find();
        if ($templateInfo){
            if ($storeUserInfo['openid']){
                $sendData = [
                    'template_id' => $templateInfo['template_id'],
                    'appid' => $platformInfo['xcx_appid'],
                    'appsecret' => $platformInfo['xcx_appsecret'],
                    'openid' => $storeUserInfo['openid'],
                    'name' => '购买票根',
                    'amount' => $TicketOrderInfo['price']
                ];

                $Payment = new \app\admin\model\template\Payment();
                $Payment->send($sendData);
            }
        }

        echo 'success ';exit;

    }

    // 收款记录
    public function orderLogList(){

        $request = $this->request;
        $param = $request->param();
        $orderModel =  new OrderLog();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        if (isset($param['store_id']) &&$param['store_id'] ){
            $where[] = ['store_id' ,'=',$param['store_id'] ];
        }

        if (isset($param['account_id']) &&$param['account_id'] ){
            $accountModel = new StoreAccount();
            $accountInfo  = $accountModel->where(['id' => $param['account_id']])->find();
            if ($accountInfo['account_type'] == 1){
                $where[] = ['store_id' ,'=',$accountInfo['store_id'] ];
            }else{
                $where[] = ['account_id' ,'=',$param['account_id'] ];
            }
            //$where = ['account_id' =>$param['uid'] ];
        }
        if (isset($param['uid']) && $param['uid']){
            $where[] = ['uid' ,'=',$param['uid'] ];
        }

        if (isset( $param['order_number'])  && $param['order_number']){
               $where[] = ['order_number' ,'=',$param['order_number'] ];
        }
        if (isset( $param['way_code'])  && $param['way_code']){
            $where[] = ['way_code' ,'=',$param['way_code'] ];
        }

        if (isset( $param['buy_type'])  && $param['buy_type']){
            $where[] = ['buy_type' ,'=',$param['buy_type'] ];
        }

        if (isset($param['write_type'])&& $param['write_type']){
            $where[] = ['write_type', '=',$param['write_type'] ];
        }


        if (isset( $param['type'])  && $param['type']){

            $where[] = ['type', '=',$param['type']];
        }
        if (isset( $param['pay_way'])  && $param['pay_way']){
            $where[] = ['pay_way', '=',$param['pay_way']];
        }
        if (isset( $param['start_time'])  && $param['start_time']){

            $zuixiao =  strtotime($param['start_time']);
            $zuida = strtotime(date('Y-m-d')." +1 month -1 day");


            $where[] = ['create_time', '>=',$zuixiao ];
            $where[] = ['create_time', '<=',$zuida ];
        }
        $total = $orderModel->where($where)->count();
        $list = $orderModel->where($where)->limit(($pindex - 1) * $psize, $psize)->select();

        $totalArray['consumer_total']  = $total;
        $totalArray['total_amount']  =$orderModel->where($where)->sum('total_amount');
        $totalArray['amount']  =$orderModel->where($where)->sum('pay_amount');
        $totalArray['aliyun_amount']  =$orderModel->where($where)->where(['pay_way' =>'aliyun' ])->sum('pay_amount');
        $totalArray['wechat_amount']  =$orderModel->where($where)->where(['pay_way' =>'wechat' ])->sum('pay_amount');

        $totalArray['deduct_amount']  =   (float)bcsub($totalArray['total_amount'], $totalArray['amount'],2);
        foreach ($list as $key => $value){
            $userModel = new \app\admin\model\User();
            $list[$key]['userInfo'] = $userModel->where(['id' => $value['uid']])->find();
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'statistics' => $totalArray,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));

    }

    public function refund(){
        $request = $this->request;
        $param = $request->param();
        if ($param['type'] == 1){ // 商品订单
            $orderModel =  new Order();
            $orderInfo = $orderModel->where(['id' =>$param['id'] ])->find();
            $storeModel =  new \app\admin\model\Store();
            $storeInfo = $storeModel->where(['id' => $orderInfo['store_id']])->find();
            $requestData = [
                'mchNo' => $storeInfo['mch_no'],
                'appId' => $storeInfo['app_id'],
                'mchOrderNo' =>$orderInfo['order_number'],
                'mchRefundNo' =>  getPayNo('tu'),
                'refundAmount' => intval($orderInfo['pay_amount'] *100),
                'currency' => 'cny',
                'refundReason' => '用户退款',
                'reqTime' => time() * 1000,
                'version' => '1.0',
                'signType'=> 'MD5',
            ];
            ksort($requestData);
            $dataString= '';
            foreach ($requestData as $key => $v){
                $dataString.= $key.'='.$v.'&';
            }
            $dataString .= 'key='.$storeInfo['private_key'];
            $sign =  strtoupper(md5($dataString));
            $requestData['sign'] = $sign;
            $result  = jsonPost('https://pay.ympay.cn/api/refund/refundOrder',[],$requestData);



        }elseif($param['type'] == 2){ // 优惠券
            $ConsumerClaimLogModel =  new ConsumerClaimLog();
            $orderInfo = $ConsumerClaimLogModel->where(['id' =>$param['id'] ])->find();
            $storeModel =  new \app\admin\model\Store();
            $storeInfo = $storeModel->where(['id' => $orderInfo['write_store_id']])->find();
            $requestData = [
                'mchNo' => $storeInfo['mch_no'],
                'appId' => $storeInfo['app_id'],
                'mchOrderNo' =>$orderInfo['order_number'],
                'mchRefundNo' =>  getPayNo('tu'),
                'refundAmount' => intval($orderInfo['price'] *100),
                'currency' => 'cny',
                'refundReason' => '用户退款',
                'reqTime' => time() * 1000,
                'version' => '1.0',
                'signType'=> 'MD5',
            ];
            ksort($requestData);
            $dataString= '';
            foreach ($requestData as $key => $v){
                $dataString.= $key.'='.$v.'&';
            }
            $dataString .= 'key='.$storeInfo['private_key'];
            $sign =  strtoupper(md5($dataString));
            $requestData['sign'] = $sign;
            $result  = jsonPost('https://pay.ympay.cn/api/refund/refundOrder',[],$requestData);



        }else if ($param['type'] == 3){ // 票根
            $TicketOrderModel =  new TicketOrder();
            $orderInfo = $TicketOrderModel->where(['id' =>$param['id'] ])->find();
            $storeModel =  new \app\admin\model\Store();
            $storeInfo = $storeModel->where(['id' => $orderInfo['store_id']])->find();
            $requestData = [
                'mchNo' => $storeInfo['mch_no'],
                'appId' => $storeInfo['app_id'],
                'mchOrderNo' =>$orderInfo['order_number'],
                'mchRefundNo' =>  getPayNo('tu'),
                'refundAmount' => intval($orderInfo['price'] *100),
                'currency' => 'cny',
                'refundReason' => '用户退款',
                'reqTime' => time() * 1000,
                'version' => '1.0',
                'signType'=> 'MD5',
            ];
            ksort($requestData);
            $dataString= '';
            foreach ($requestData as $key => $v){
                $dataString.= $key.'='.$v.'&';
            }
            $dataString .= 'key='.$storeInfo['private_key'];
            $sign =  strtoupper(md5($dataString));
            $requestData['sign'] = $sign;
            $result  = jsonPost('https://pay.ympay.cn/api/refund/refundOrder',[],$requestData);

        }elseif($param['type'] == 4){ // 消费券
            $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
            $consumerClaimLogInfo  = $consumerClaimLogModel->where(['id'=>$param['id'] ])->find();
            $platformModel = new Platform();
            $platformInfo = $platformModel->where(['id' =>$consumerClaimLogInfo['platform_id'] ])->find();
            if (empty($platformInfo['xcx_appid'])){
                return result(- 1, '支付配置有误,请联系管理员' );
            }
            $UserModel = new \app\admin\model\User();
            $userInfo = $UserModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
            $domain = $request->domain();
            $data = [
                'serial_number' => $platformInfo['pay_serial_no'],
                'order_sn' => $consumerClaimLogInfo['order_number'],
                'price' => $consumerClaimLogInfo['price'],
                'pay_key' => $platformInfo['pay_key'],
            ];
            $wechatPayService = new WechatpayService();


            if ($platformInfo['pay_type'] == 2){
                $data['sp_appid'] = $platformInfo['pay_service_appid'];
                $data['sp_mchid'] = $platformInfo['pay_service_mchid'];
                $data['sub_appid'] = $platformInfo['xcx_appid'];
                $data['sub_mchid'] = $platformInfo['pay_mchid'];

                  //  $data['openid'] =$userInfo['openid'];
                    $result =   $wechatPayService->mrefunds($data);

            }else{
                $data['appid'] = $platformInfo['xcx_appid'];
                $data['mchid'] = $platformInfo['pay_mchid'];

                    //$data['openid'] =$userInfo['openid'];
                    $result =  $wechatPayService->refunds($data);

            }
            if ($result['code'] == 1) {
                return result(0, '成功',$result['data']);
            } else {
                return result(-1,$result['msg']);
            }

        }else{
            $consumerClaimLogModel = new \app\admin\model\CouponOrder();
            $consumerClaimLogInfo  = $consumerClaimLogModel->where(['id'=>$param['id'] ])->find();
            $platformModel = new Platform();
            $platformInfo = $platformModel->where(['id' =>$consumerClaimLogInfo['platform_id'] ])->find();
            if (empty($platformInfo['xcx_appid'])){
                return result(- 1, '支付配置有误,请联系管理员' );
            }
            $UserModel = new \app\admin\model\User();
            $userInfo = $UserModel->where(['id' => $consumerClaimLogInfo['uid']])->find();
            $domain = $request->domain();
            $data = [
                'serial_number' => $platformInfo['pay_serial_no'],
                'order_sn' => $consumerClaimLogInfo['order_number'],
                'price' => $consumerClaimLogInfo['price'],
                'pay_key' => $platformInfo['pay_key'],
              //  'openid' => $userInfo['openid']
            ];
            $wechatPayService = new WechatpayService();
            if ($platformInfo['pay_type'] == 2){

                $data['sp_appid'] = $platformInfo['pay_service_appid'];
                $data['sp_mchid'] = $platformInfo['pay_service_mchid'];
                $data['sub_appid'] = $platformInfo['xcx_appid'];
                $data['sub_mchid'] = $platformInfo['pay_mchid'];
                $result =   $wechatPayService->mrefunds($data);

            }else {


                $data['appid'] = $platformInfo['xcx_appid'];
                $data['mchid'] = $platformInfo['pay_mchid'];

                $data['payer_client_ip'] = $_SERVER['REMOTE_ADDR'];

                $result = $wechatPayService->refunds($data);
            }



        }
    }

    public function useGoods(){
        $request = $this->request;
        $param = $request->param();
        $GoodsOrder =  new GoodsOrder();
        if(isset($param['id']) && $param['id']){
            $GoodsOrderInfo =   $GoodsOrder->where(['id' =>$param['id'] ]) ->find();
        }else{
            $GoodsOrderInfo =   $GoodsOrder->where(['code' =>$param['code'] ]) ->find();
        }
        $goodsModel = new \app\admin\model\Goods();
        $goodsInfo  =$goodsModel->where(['id' =>$GoodsOrderInfo['goods_id'] ])->find();
        $account = new StoreAccount();
        $accountInfo =  $account->where(['id' => $param['account_id']])->find();
        if ($accountInfo['store_id'] != $GoodsOrderInfo['store_id'] ){
            return result(0, '此商品不属于此该店铺');
        }
        $platform  = new Platform();
        $platformInfo =  $platform->where(['id' => $GoodsOrderInfo['platform_id']])->find();
        $userModel = new \app\admin\model\User();
        $userInfo  = $userModel->where(['id' => $GoodsOrderInfo['uid']])->find();
        $withdraw = new \app\admin\model\template\Ticket();
        $templateModel   = new \app\admin\model\Template();
        $templateInfo = $templateModel->where(['name'=>'ticket',
            'platform_id'=> $GoodsOrderInfo['platform_id']])->find();
        if ($userInfo['openid']){
            $sendData = [
                'template_id' => $templateInfo['template_id'],
                'appid' => $platformInfo['xcx_appid'],
                'appsecret' => $platformInfo['xcx_appsecret'],
                'openid' => $userInfo['openid'],
                'price' => $GoodsOrderInfo['price'],
                'amount' => $GoodsOrderInfo['amount'],
                'name' => '商品--'.$goodsInfo['name'],
            ];
            $withdraw->send($sendData);
        }
        $GoodsOrder->where(['id' =>$param['id'] ])->update([
            'is_use' => 2,
            'account_id' => $param['account_id'],
            'operation_uid' => $param['operation_uid'],
        ]);
        return result(0, '核销成功');
    }



}